package com.manster.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.manster.entity.SysMenu;
import com.manster.entity.SysRole;
import com.manster.entity.SysUser;
import com.manster.mapper.SysUserMapper;
import com.manster.service.SysMenuService;
import com.manster.service.SysRoleService;
import com.manster.service.SysUserService;
import com.manster.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author manster
 * @since 2022-03-13
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    SysRoleService roleService;

    @Autowired
    SysMenuService menuService;

    @Autowired
    RedisUtils redisUtils;

    @Override
    public SysUser getByUsername(String username) {
        return getOne(new QueryWrapper<SysUser>().eq("username", username));
    }

    //根据用户id获取权限
    @Override
    public String getUserAuthorityInfo(Long userId) {

        SysUser sysUser = baseMapper.selectById(userId);

        //有缓存直接取缓存
        if(redisUtils.hasKey("GrantedAuthority:" + sysUser.getUsername())){
            return (String) redisUtils.get("GrantedAuthority:" + sysUser.getUsername());
        }

        //角色(ROLE_admin)，菜单权限(sys:user:list)

        //ROLE_admin,ROLE_normal,sys:user:list,...
        StringBuilder authority = new StringBuilder();
        //获取角色
        //select * from sys_role where id in(select role_id from sys_user_role where user_id = 1);
        List<SysRole> roles = roleService.list(new QueryWrapper<SysRole>()
                .inSql("id", "select role_id from sys_user_role where user_id =" + userId));

        if(roles.size() > 0){
            String roleCodes = roles.stream().map(r -> "ROLE_" + r.getCode()).collect(Collectors.joining(","));
            authority.append(roleCodes);
        }

        //获取菜单权限

        //根据用户id获取菜单
        List<Long> menuIds = baseMapper.getNavMenuIds(userId);
        if(menuIds.size() > 0){
            authority.append(",");
            List<SysMenu> menus = menuService.listByIds(menuIds);
            String menuPerms = menus.stream().map(m -> m.getPerms()).collect(Collectors.joining(","));
            authority.append(menuPerms);
        }

        redisUtils.set("GrantedAuthority:" + sysUser.getUsername(), authority, 60 * 60);

        return authority.toString();
    }

    //删除用户权限信息缓存
    @Override
    public void clearUserAuthorityInfo(String username) {
        redisUtils.del("GrantedAuthority:" + username);
    }

    //角色信息发生改变，将缓存进行删除
    @Override
    public void clearUserAuthorityInfoByRoleId(Long roleId) {

        List<SysUser> sysUsers = list(new QueryWrapper<SysUser>().inSql("id", "select user_id from sys_user_role where role_id = " + roleId));

        sysUsers.forEach(u -> clearUserAuthorityInfo(u.getUsername()));

    }

    //权限信息发生改变，将缓存进行删除
    @Override
    public void clearUserAuthorityInfoByMenuId(Long menuId) {
        List<SysUser> sysUsers = baseMapper.listByMenuId(menuId);
    }

    //根据邮箱获取用户
    @Override
    public SysUser getByEmail(String email) {
        return baseMapper.selectOne(new QueryWrapper<SysUser>().eq("email",email));
    }

}
